from flask import Flask, render_template, request, jsonify
import requests

app = Flask(__name__)


def get_bilibili_fans(uid):
    url = f"https://api.bilibili.com/x/relation/stat?vmid={uid}&jsonp=jsonp"
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"
    }

    try:
        response = requests.get(url, headers=headers)
        response.raise_for_status()
        data = response.json()
        if data['code'] == 0:
            return data['data']['follower']
        else:
            print(f"API返回错误: {data['message']}")
            return None
    except Exception as e:
        print(f"请求失败: {e}")
        return None


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/get_fans', methods=['POST'])
def get_fans():
    uid = request.form.get('uid')
    if not uid:
        return jsonify({"error": "UID不能为空"}), 400

    fans = get_bilibili_fans(uid)
    if fans is not None:
        return jsonify({"fans": fans})
    else:
        return jsonify({"error": "无法获取粉丝数"}), 500


if __name__ == '__main__':
    app.run(debug=True)